/*
* @Author: dengjiayao
* @Date:   2017-08-28 17:19:29
 * @Last Modified by: songwh
 * @Last Modified time: 2018-01-03 17:01:41
*/
import { modal } from 'vue-strap'
import { showMsg, saveClasses } from '../../vuex/action'

export default {
  data() {
    return {
      showModal: false,
      actionType: 'ADD', // ADD or UPDATE
      form: {
        top: 0,
        title: '',
        summary: '',
        listPicUrl: '',
        headPicUrl: '',
        shopPicUrl: '',
        shopUrl: '',
        topicId: '',
        frequency: '',
        highlights: '',
        lockedInfo: '',
        timetablePicUrl: '',
        lecturerIntro: '',
        suitableFor: ''
      }
    }
  },
  components: {
    'vue-modal': modal
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xSave: saveClasses
    }
  },
  methods: {
    valid() {
      let fields = ['title', 'summary', 'shopUrl', 'topicId', 'frequency']
      for (let k of fields) {
        let v = this.form[k] + ''
        if (v.length === 0) {
          return Promise.reject({
            error_msg: '*标识的均为必填项'
          })
        }
      }
      if (this.actionType === 'ADD') {
        fields = ['listPicFile', 'headPicFile', 'shopPicFile']
        for (let k of fields) {
          let files = this.$els[k].files
          if (files.length === 0) {
            return Promise.reject({
              error_msg: '*标识的均为必填项'
            })
          }
        }
      }
      return Promise.resolve()
    },
    isFile(k) {
      let fields = ['highlights', 'lecturerIntro', 'suitableFor']
      for (let f of fields) {
        if(f === k){
          return true
        }
      }
      return false
    },
    submit() {
      this.valid()
        .then(() => {
          let form = this.form
          let formData = new FormData()
          for (let k in form) {
            let isFile = this.isFile(k)
            if (/picurl/i.test(k)) {
              k = k.replace('Url', 'File')
              let file = this.$els[k].files[0]
              if (file) {
                formData.append(k, file)
              }
            } else if(isFile) {
              k += 'File'
              let file = this.$els[k].files[0]
              if (file) {
                formData.append(k, file)
              }
            } else {
              formData.append(k, this.form[k])
            }
          }
          return this.xSave(formData)
        })
        .then(() => {
          this.showModal = false
        })
        .catch(res => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
